from flask import Flask, render_template, jsonify, request
import requests
import json
import re
import time

app = Flask(__name__,
            template_folder='./',
            static_folder='./',
            static_url_path='/')
url = "https://norhub.com.cn/api/admin/topic/list?page=1&limit=10000&status=0"
headers = {
    "X-User-Token": "968e7f29b6d946e6977d5c0fe7e32b47",
    "Accept": "application/json, text/plain, */*",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
    }

@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')

@app.route('/v1/cron/job/sorts', methods=['GET','POST'])
def sort_api():
    '''获取类型'''
    response = {'status': False}
    try:
        # 获取全部
        res = requests.get(url, headers = headers)
        our_deck = json.loads(res.text)
        ids = 0
        res = []
        classs_list = []
        # 条件获取
        if our_deck["success"] == True:
            datas = our_deck["data"]["results"]
            for item in datas:
                if item["status"] == 0 and item["node"]["nodeId"] == 1:
                    name = re.findall(r'名称[\s:：]+?(.+?卡组\d?\d?)',item["content"])
                    classs = re.findall(r'类型[\s:：]+?(.+)',item["content"])
                    comment = re.findall(r'说明[\s:：]+?(.+)',item["content"])
                    source = re.findall(r'来自[\s:：]+?(.+)',item["content"])
                    images = [img["url"] for img in item['imageList']]
                    create_time = time.strftime("%Y-%m-%d %H:%M", time.localtime(int(str(item["createTime"])[:10])))
                    images += ["" for i in range(5-len(images))]
                    if name:
                        res_json = {}
                        res_json['id'] = ids
                        res_json['code'] = ''
                        res_json['comment'] = comment
                        res_json['isdelflag'] = False
                        res_json['modtime'] = create_time
                        res_json['name'] = name
                        res_json['original'] = source
                        res_json['sort'] = classs
                        res_json['id'] = ids
                        res_json['url1'] = images[0]
                        res_json['url2'] = images[1]
                        res_json['url3'] = images[2]
                        if classs not in classs_list:
                            classs_list.append(classs)
                            res.append(res_json)
                        ids += 1
        count = len(res)
        response['status'] = True
        response['code'] = 0
        response['data'] = res
        response['count'] = count
    except Exception as e:
        response['code'] = 4000
        response['msg'] = str(e)
    return jsonify(response)

@app.route('/v1/cron/job/job_plots', methods=['GET'])
def data_api():
    '''获取卡组'''
    response = {'status': False}
    try:
        searchParams = request.values.get('searchParams')
        res = requests.get(url, headers = headers)
        our_deck = json.loads(res.text)
        ids = 0
        res = []
        if searchParams:
            # 条件获取
            searchParams = json.loads(searchParams)
            if our_deck["success"] == True:
                datas = our_deck["data"]["results"]
                for item in datas:
                    if item["status"] == 0 and item["node"]["nodeId"] == 1:
                        name = re.findall(r'名称[\s:：]+?(.+?卡组\d?\d?)',item["content"])
                        classs = re.findall(r'类型[\s:：]+?(.+)',item["content"])
                        comment = re.findall(r'说明[\s:：]+?(.+)',item["content"])
                        source = re.findall(r'来自[\s:：]+?(.+)',item["content"])
                        images = [img["url"] for img in item['imageList']]
                        create_time = time.strftime("%Y-%m-%d %H:%M", time.localtime(int(str(item["createTime"])[:10])))
                        images += ["" for i in range(5-len(images))]
                        if name:
                            res_json = {}
                            res_json['id'] = ids
                            res_json['code'] = ''
                            res_json['comment'] = comment
                            res_json['isdelflag'] = False
                            res_json['modtime'] = create_time
                            res_json['name'] = name
                            res_json['original'] = source
                            res_json['sort'] = classs
                            res_json['id'] = ids
                            res_json['url1'] = images[0]
                            res_json['url2'] = images[1]
                            res_json['url3'] = images[2]
                            if (not searchParams['name'] or searchParams['name'] in name[0]) and\
                                (not searchParams['sort'] or searchParams['sort'] in classs[0]) and\
                                    (not searchParams['original'] or searchParams['original'] in source[0]):
                                res.append(res_json)
                            ids += 1
            count = len(res)
        else:
            # 获取全部
            if our_deck["success"] == True:
                datas = our_deck["data"]["results"]
                for item in datas:
                    if item["status"] == 0 and item["node"]["nodeId"] == 1:
                        name = re.findall(r'名称[\s:：]+?(.+?卡组\d?\d?)',item["content"])
                        classs = re.findall(r'类型[\s:：]+?(.+)',item["content"])
                        comment = re.findall(r'说明[\s:：]+?(.+)',item["content"])
                        source = re.findall(r'来自[\s:：]+?(.+)',item["content"])
                        images = [img["url"] for img in item['imageList']]
                        create_time = time.strftime("%Y-%m-%d %H:%M", time.localtime(int(str(item["createTime"])[:10])))
                        images += ["" for i in range(5-len(images))]
                        if name:
                            res_json = {}
                            res_json['id'] = ids
                            res_json['code'] = ''
                            res_json['comment'] = comment
                            res_json['isdelflag'] = False
                            res_json['modtime'] = create_time
                            res_json['name'] = name
                            res_json['original'] = source
                            res_json['sort'] = classs
                            res_json['id'] = ids
                            res_json['url1'] = images[0]
                            res_json['url2'] = images[1]
                            res_json['url3'] = images[2]
                            res.append(res_json)
                            ids += 1
            count = len(res)
        response['status'] = True
        response['code'] = 0
        response['data'] = res
        response['count'] = count
    except Exception as e:
        response['code'] = 4000
        response['msg'] = str(e)
    return jsonify(response)

if __name__ == '__main__':
    app.run('0.0.0.0',9001,debug=False,threaded=True)
